package com.qxzn.app.page.util;

import android.Manifest;
import android.content.DialogInterface;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.qxzn.app.page.view.MyDialog;
import com.qxzn.app.util.AppUtil;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

public class PermissionUtil {

    /////////////////权限下标///////////////////////////
    public static final int CAMERA = 0;
    public static final int WRITE_EXTERNAL_STORAGE = 1;
    public static final int READ_EXTERNAL_STORAGE = 2;
    public static final int RECORD_AUDIO = 3;
    public static final int ACCESS_FINE_LOCATION = 4;
    public static final int CALL_PHONE = 5;
    public static final int READ_PHONE_STATE = 6;
    public static final String[] permissions = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.READ_PHONE_STATE};
    public static final String[] permissionsRemark = new String[]{"相机",
            "存储",
            "",
            "麦克风",
            "位置信息",
            "拨打电话",
            "本机识别码"};
    /////////////////权限下标///////////////////////////
    private static PermissionUtil util;
    private FragmentActivity mActivity;
    private String title = "权限请求";
    private String message = "为了您能拥有更好的体验，请允许APP获取%s\n可通过点击《去设置》-《权限管理》，并设置该页面的权限为允许后返回即可";
    private String confirmText = "去 设 置";
    private String cancelText = "下次再说";

    private PermissionUtil() {
    }

    public static PermissionUtil getInstant() {
        if (util == null) {
            synchronized (PermissionUtil.class) {
                if (util == null) {
                    util = new PermissionUtil();
                }
            }
        }
        return util;
    }

    public PermissionUtil requestPermission(final Consumer<Permission> consumer, final PermissionGrantListener grantListener, final Integer... permissionIndex) {
        requestPermission(consumer, grantListener, null, null, permissionIndex);
        return this;
    }

    public PermissionUtil requestPermission(final Consumer<Permission> consumer, final PermissionGrantListener grantListener, final DialogInterface.OnClickListener confirmClick, final DialogInterface.OnClickListener cancelClick, final Integer... permissionIndex) {
        String permissions[] = null;
        if (permissionIndex != null && permissionIndex.length > 0) {
            permissions = new String[permissionIndex.length];
            for (int i = 0; i < permissionIndex.length; i++) {
                permissions[i] = PermissionUtil.permissions[permissionIndex[i]];
            }
        }
        new RxPermissions(mActivity)
                .requestEachCombined((permissions == null || permissions.length == 0) ? PermissionUtil.permissions : permissions)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        AppUtil.showLog("PermissionUtil.accept");
                        if (consumer != null) {
                            AppUtil.showLog("PermissionUtil.consumer != null");
                            consumer.accept(permission);
                        } else {
                            AppUtil.showLog("PermissionUtil.consumer == null");
                            if (permission.granted) {
                                // All permissions are granted !
                                if (grantListener != null) {
                                    grantListener.onPermissionGrant();
                                }
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // At least one denied permission without ask never again
                                requestPermission(consumer, grantListener, permissionIndex);
                            } else {
                                // At least one denied permission with ask never again
                                // Need to go to the settings
//                            ToastUtil.showLongToast(AutoLoginActivity.this, "请允许权限：" + permission.name);
//                            gotoAppDetailIntent(AutoLoginActivity.this);
                                showPermissionNeedDialog(confirmClick, cancelClick, permissionIndex);
                            }
                        }
                    }
                });
        return this;
    }

    public void showPermissionNeedDialog(final DialogInterface.OnClickListener confirmClick, final DialogInterface.OnClickListener cancelClick, final Integer... permissionIndex) {
        String permissions = "";
        if (permissionIndex != null) {
            for (int i = 0; i < permissionIndex.length; i++) {
                if (i == 0) {
                    permissions += PermissionUtil.permissionsRemark[permissionIndex[i]];
                } else {
                    permissions += "、" + PermissionUtil.permissionsRemark[permissionIndex[i]];
                }
            }
        }
        MyDialog.Builder builder = new MyDialog.Builder(mActivity);
//        builder.setContentView(LayoutInflater.from(mActivity).inflate(R.layout.dialog_no_title_vip, null));
        builder.setMessage(String.format(message, TextUtils.isEmpty(permissions) ? "必要权限" : "“" + permissions + "权限”"));
        builder.setTitle(title);
        builder.setCancelAble(false);
        builder.setCanceledOnTouchOutside(false);
        builder.setPositiveButton(new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                AppUtil.showLog("PermissionUtil.setPositiveButton");
                // 设置你的操作事项
                if (confirmClick != null) {
                    confirmClick.onClick(dialog, which);
                } else {
//                    CommonUtil.gotoAppDetailIntent(mActivity);
                    dialog.dismiss();
                    dialog = null;
                }
            }
        });

        builder.setNegativeButton(new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                AppUtil.showLog("PermissionUtil.setNegativeButton");
                if (cancelClick != null) {
                    cancelClick.onClick(dialog, which);
                } else {
                    dialog.dismiss();
                    dialog = null;
                }
            }
        });

        builder.create().show();
    }

    public void destroy() {
        mActivity = null;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setConfirmText(String confirmText) {
        this.confirmText = confirmText;
    }

    public void setCancelText(String cancelText) {
        this.cancelText = cancelText;
    }

    public PermissionUtil setActivity(FragmentActivity mActivity) {
        this.mActivity = mActivity;
        return this;
    }

    public interface PermissionGrantListener {
        void onPermissionGrant();
    }

}
